package com.neuedu.autosale.sys.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.neuedu.autosale.entity.Emp;
import com.neuedu.autosale.sys.service.EmpService;
import com.neuedu.autosale.util.Const;

@Controller
@SessionAttributes(value = { Const.SESSION_EMP, Const.LOGIN_FAIL_COUNT, Const.ERROR_MSG })
public class LoginController {
	@Autowired
	private EmpService empService;

	@GetMapping("/emp/login")
	public String login() {
		return "login";
	}

	@GetMapping("/error")
	public String error() {
		return "error";
	}

	@GetMapping("/emp/logout")
	public String doLogout(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		session.invalidate();
//		Cookie cookie = new Cookie("JSESSIONID", null);
//		cookie.setPath(request.getContextPath());
//		cookie.setMaxAge(0);
//		// 把cookie响应返回客户端，浏览器客户端收到后会保存cookie
//		response.addCookie(cookie);
		return "redirect:/emp/login";
	}

	@PostMapping("/emp/login")
	public String doLogin(Emp emp, ModelMap modelMap) {
		Integer counter = (Integer) modelMap.get(Const.LOGIN_FAIL_COUNT);
		if (counter != null && ++counter > 5) {
			modelMap.addAttribute(Const.ERROR_MSG, "登陆失败次数过多，请稍后再试！");
			return "redirect:/error";
		}
		Emp loginemp = empService.login(emp);
//		System.out.println(loginemp);
		if (loginemp != null) {
			modelMap.addAttribute(Const.SESSION_EMP, loginemp);
			modelMap.remove(Const.LOGIN_FAIL_COUNT);
			modelMap.remove(Const.ERROR_MSG);
			return "redirect:/";
		} else {
			modelMap.addAttribute(Const.LOGIN_FAIL_COUNT, counter);
			return "redirect:/emp/login";
		}
	}

}
